//
//  MapViewManager.m
//  PigMarket
//
//  Created by mac on 2019/5/20.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "MapViewManager.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <MAMapKit/MAMapKit.h>
#import <AMapSearchKit/AMapSearchKit.h>

static MapViewManager *instance = nil;
@interface MapViewManager ()<MAMapViewDelegate,AMapSearchDelegate>
/**
 map
 */
@property (nonatomic , strong) MAMapView *mapView;
/**
 大头针
 */
@property (nonatomic, strong) UIImageView *centerAnnotationView;
/**
 搜索
 */
@property (nonatomic, strong) AMapSearchAPI *search;
/**
 locationBtn
 */
@property (nonatomic , strong) UIButton *locationBtn;
/**
 划线
 */
@property (nonatomic, strong) MAPolyline *commonPolyline;
/**
 commonPolylineArr
 */
@property (nonatomic , strong) NSMutableArray *commonPolylineArr;
/**
 firstLocation
 */
@property (nonatomic , assign) BOOL isFirstLocation;
/**
 count
 */
@property (nonatomic , assign) NSUInteger commonPolylineCount;
/**
 搜索结果Arr
 */
@property (nonatomic , strong) NSMutableArray *searchArr;
/**
 当前城市
 */
@property (nonatomic , strong) NSString *currentCity;
/**
 拼接省市区
 */
@property (nonatomic , strong) NSString *proviceCityDistrict;
@end
@implementation MapViewManager

+ (instancetype)sharedManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[MapViewManager alloc] init];
    });
    return instance;
}
#pragma mark - init method
- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initSearch];
        [self initMapView];
        [self initLayout];
    }
    return self;
}
- (void)initSearch {
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
}
- (void)initMapView{
    // 添加子控件
    self.mapView = [[MAMapView alloc] init];
    [self addSubview:self.mapView];
    
    //代理
    self.mapView.delegate = self;
    
    //地图需要v4.5.0及以上版本才必须要打开此选项（v4.5.0以下版本，需要手动配置info.plist）
    [AMapServices sharedServices].enableHTTPS = YES;
    
    //开启定位
    self.mapView.showsUserLocation = YES;
    self.mapView.userTrackingMode = MAUserTrackingModeNone;
    
    //标记是否是第一次定位
    self.isFirstLocation = YES;
    
    //init大头针
    [self initCenterView];

    //定位按钮
    [self.mapView addSubview:self.locationBtn];
}


//大头针
- (void)initCenterView {
    self.centerAnnotationView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"address_bigpin"]];
    [self.mapView addSubview:self.centerAnnotationView];
}


- (void)initLayout {
    // 布局子控件
    [self.mapView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.mas_equalTo(0);
    }];
    [self.centerAnnotationView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.mapView.mas_centerX);
        make.centerY.mas_equalTo(self.mapView.mas_centerY).offset(-12);
    }];
    
    [self.locationBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.right.mas_equalTo(-15);
        make.size.mas_equalTo(CGSizeMake(32, 32));
    }];
    
}
#pragma mark - 配送范围赋值 （经纬度数组）
- (void)configMapWithDataArr:(NSMutableArray *)dataArr failureBlock:(void (^)(BOOL))faileureBlock{
    
   //改变缩放级别
    [self.mapView setZoomLevel:12 animated:YES];

    PMLog(@"配送范围赋值");
    for (int i = 0; i < dataArr.count; i++) {
        NSMutableArray *tempArr = dataArr[i];
        
        //构造折线数据对象
        self.commonPolylineCount = tempArr.count;
        CLLocationCoordinate2D commonPolylineCoords[self.commonPolylineCount];
        
        for (int i = 0; i < tempArr.count; i++) {
            LongAndLat *model = nil;
            for (NSUInteger i = 0; i < tempArr.count; i ++) {
                model = tempArr[i];
                commonPolylineCoords[i].latitude = [model.latitude doubleValue];
                commonPolylineCoords[i].longitude = [model.longitude doubleValue];
            }
        }
        //构造折线对象
        MAPolyline *commonPolyline = [MAPolyline polylineWithCoordinates:commonPolylineCoords count:self.commonPolylineCount];
        
        //在地图上添加折线对象
        [self.mapView addOverlay: commonPolyline];
        
        self.commonPolyline = commonPolyline;
        
        [self.commonPolylineArr addObject:self.commonPolyline];
        
        self.locationFailureBlock = faileureBlock;
    }
}
#pragma mark - 用户搜索地址
- (void)userSearchAddressWithInputAddress:(NSString *)address completeBlock:(void (^)(NSMutableArray *))completeBlock {
    if (address.length == 0) {
        return;
    }
    PMLog(@"用户搜索地址-userSearchAddressWithInputAddress");

    AMapInputTipsSearchRequest *tipsRequest = [[AMapInputTipsSearchRequest alloc] init];
    tipsRequest.keywords = address;
    tipsRequest.city = self.currentCity;
    PMLog(@"%@",self.currentCity);
    [self.search AMapInputTipsSearch:tipsRequest];
    self.userSearchAddressBlock = completeBlock;
}
#pragma mark - targetAction
- (void)locationClick {
    
    [self.mapView setCenterCoordinate:self.mapView.userLocation.coordinate animated:YES];
}
//判断定位权限是否开启
- (void)checkLocationAuthorization {
    
    
    CLAuthorizationStatus authorizationStatus = [CLLocationManager authorizationStatus];
    /*
     kCLAuthorizationStatusNotDetermined:用户尚未对该应用程序做出选择
     kCLAuthorizationStatusRestricted:此应用程序无权使用位置服务。由于位置服务的活动限制，用户不能更改此状态，并且可能没有亲自拒绝授权
     kCLAuthorizationStatusDenied:用户已显式拒绝此应用程序的授权，或在设置中禁用位置服务。
     kCLAuthorizationStatusAuthorizedAlways:一直使用
     kCLAuthorizationStatusAuthorizedWhenInUse:使用时使用
     kCLAuthorizationStatusAuthorized：用户已授权此应用程序使用位置服务。这个值在iOS、tvOS和watchOS上是不推荐或禁止的。它应该在MacOS上使用。
     */
    switch (authorizationStatus) {
        case kCLAuthorizationStatusAuthorizedAlways:
            
            break;
        case kCLAuthorizationStatusAuthorizedWhenInUse:
            
            break;
        case kCLAuthorizationStatusNotDetermined://用户尚未对该应用程序做出选择
        {
            
        }
            break;
        default:
            break;
    }
}
#pragma mark --------------------------------- delegate ------------------------------
//---------------------- location delegate-----------
//定位失败
- (void)mapView:(MAMapView *)mapView didFailToLocateUserWithError:(NSError *)error {
//    if ([CLLocationManager locationServicesEnabled]) { //定位是否允许
//        [[AlertAction sharedInstance] showAlertWithTitle:@"无法获取位置信息" message:@"请在iPhone的设置-隐私-位置中允许访问位置"
//                                         confirmBtnTitle:@"前往设置" confirmBlock:^{
//                                             [self pushPhoneSetting];
//                                         } cancelBlock:nil];
//        return;
//    }
    if (self.locationFailureBlock) {
        self.locationFailureBlock(YES);
    }
    
}
//定位改变时
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation{

    if(!updatingLocation) return ;
    
    if (userLocation.location.horizontalAccuracy < 0)
    {
        return ;
    }
    
    // only the first locate used.
    if (self.isFirstLocation)
    {
        PMLog(@"didUpdateUserLocation");
        self.isFirstLocation = NO;
        [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude)];
        
        //定位当前位置  和  搜索周围poi
        [self actionSearchAroundAt:userLocation.location.coordinate];
    }
}
//画折线
- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay {
    
    if ([overlay isKindOfClass:[MAPolyline class]]) {
        PMLog(@"rendererForOverlay");
        
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:overlay];
        
        polylineRenderer.lineWidth = 4.f;
        polylineRenderer.strokeColor = [UIColor primaryColor];
        //虚线
        polylineRenderer.lineDashPattern = @[@10, @10];
        polylineRenderer.lineDashPhase = 0;
        
        return polylineRenderer;
    }
    return nil;
}
//地图移动 ，修改大头针的位置
- (void)mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
  
    PMLog(@"地图移动 ，修改大头针的位置 - mapView regionDidChangeAnimated");
    //搜索周围
    [self actionSearchAroundAt:self.mapView.centerCoordinate];
}
// ------------------------ search delegate -----------
- (void)actionSearchAroundAt:(CLLocationCoordinate2D)coordinate
{
   //逆地理编码 获取当前位置
    [self searchReGeocodeWithCoordinate:coordinate];
    
    //根据中心点坐标来搜周边的POI.
    [self searchPoiWithCenterCoordinate:coordinate];
    
    //大头针动画
    [self centerAnnotationAnimimate];
}
//逆地理编码 获取当前位置
- (void)searchReGeocodeWithCoordinate:(CLLocationCoordinate2D)coordinate
{
    PMLog(@"searchReGeocodeWithCoordinate");
    AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
    
    regeo.location = [AMapGeoPoint locationWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    regeo.requireExtension = YES;
    
    [self.search AMapReGoecodeSearch:regeo];
}
//根据中心点坐标来搜周边的POI.
- (void)searchPoiWithCenterCoordinate:(CLLocationCoordinate2D )coord
{
    PMLog(@"searchPoiWithCenterCoordinate");
    AMapPOIAroundSearchRequest*request = [[AMapPOIAroundSearchRequest alloc] init];
    
    request.location = [AMapGeoPoint locationWithLatitude:coord.latitude  longitude:coord.longitude];
    
    request.radius   = 1000;
    //住宅区：120300 学校：141200 楼宇：120200 商场：060111
//    request.types = @"120300";//楼宇
    request.sortrule = 0;
    [self.search AMapPOIAroundSearch:request];
}

//POI搜索结果
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response {
    PMLog(@"onPOISearchDone");
    
    [self.searchArr removeAllObjects];
    NSArray *nearArr = response.pois;

    [nearArr enumerateObjectsUsingBlock:^(AMapPOI * obj, NSUInteger idx, BOOL * _Nonnull stop) {
        double latitude = obj.location.latitude;
        double longitude = obj.location.longitude;
        MapSearchResult *model = [[MapSearchResult alloc] init];
        model.detailAddress = [NSString stringWithFormat:@"%@%@",self.proviceCityDistrict,obj.address];
        model.name = obj.name;
//        model.discrictCode = addressCom.adcode;
        model.latitude = latitude;
        model.longitude = longitude;
        if (idx == 0) {
            model.isCurrentLoc = YES;
        } else {
            model.isCurrentLoc = NO;
        }
        
        //判断当前点是否在可配送范围内
        CLLocationCoordinate2D currentLoc = CLLocationCoordinate2DMake(latitude, longitude);
        MAMapPoint p1 = MAMapPointForCoordinate(currentLoc);
        BOOL isInside = NO;
        for (int i = 0; i < self.commonPolylineArr.count; i++) {
            self.commonPolyline = self.commonPolylineArr[i];
            if(MAPolygonContainsPoint(p1, self.commonPolyline.points, self.commonPolylineCount)) {
                isInside = YES;
                break;
            } else {
                isInside = NO;
            }
        }
        model.isInside = isInside;
        [self.searchArr addObject:model];
    }];
    
    
    if (self.searchResultBlock) {
        self.searchResultBlock(self.searchArr);
    }
}

//地理编码查询成功
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    if (response.regeocode != nil)
    {
        PMLog(@"onReGeocodeSearchDone");
        AMapAddressComponent *addressCom = response.regeocode.addressComponent;
        if ([addressCom.province isEqualToString:addressCom.city]) {//直辖市处理
            self.proviceCityDistrict = [NSString stringWithFormat:@"%@%@",addressCom.city,addressCom.district];
        } else {
            self.proviceCityDistrict = [NSString stringWithFormat:@"%@%@%@",addressCom.province,addressCom.city,addressCom.district];
        }
        self.currentCity = addressCom.city;
     }
}
//根据关键字搜索结果
- (void)onInputTipsSearchDone:(AMapInputTipsSearchRequest *)request response:(AMapInputTipsSearchResponse *)response {
    if (response.count == 0) {
        NSMutableArray *tempArr = [[NSMutableArray alloc] init];
        if (self.userSearchAddressBlock) {
            self.userSearchAddressBlock(tempArr);
        }
        return;
    }
    PMLog(@"onInputTipsSearchDone");

    NSMutableArray *tempArr = [[NSMutableArray alloc] init];
    
    [response.tips enumerateObjectsUsingBlock:^(AMapTip *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        AMapGeoPoint *point = obj.location;
        double latitude = point.latitude;
        double longitude = point.longitude;
        UserSearchAddressResult *model = [[UserSearchAddressResult alloc] init];
        model.name = obj.name;
        model.detailAddress = [NSString stringWithFormat:@"%@%@",obj.district,obj.address];
        model.discrictCode = obj.adcode;
        model.latitude = latitude;
        model.longitude = longitude;
        model.isCurrentLoc = NO;
        //判断当前点是否在可配送范围内
        CLLocationCoordinate2D currentLoc = CLLocationCoordinate2DMake(latitude, longitude);
        MAMapPoint p1 = MAMapPointForCoordinate(currentLoc);
        BOOL isInside = NO;
        for (int i = 0; i < self.commonPolylineArr.count; i++) {
            self.commonPolyline = self.commonPolylineArr[i];
            if(MAPolygonContainsPoint(p1, self.commonPolyline.points, self.commonPolylineCount)) {
                isInside = YES;
                break;
            } else {
                isInside = NO;
            }
        }
        model.isInside = isInside;
        [tempArr addObject:model];
    }];
    
    if (self.userSearchAddressBlock) {
        self.userSearchAddressBlock(tempArr);
    }
}
//搜索失败
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error {
    NSLog(@"search error%@",error);
}

#pragma mark - ----------------------------------private method-----------------------------------------
/* 移动窗口弹一下的动画 */
- (void)centerAnnotationAnimimate
{
    [UIView animateWithDuration:0.5
                          delay:0
                        options:UIViewAnimationOptionCurveEaseOut
                     animations:^{
                         CGPoint center = self.centerAnnotationView.center;
                         center.y -= 20;
                         [self.centerAnnotationView setCenter:center];}
                     completion:nil];
    
    [UIView animateWithDuration:0.45
                          delay:0
                        options:UIViewAnimationOptionCurveEaseIn
                     animations:^{
                         CGPoint center = self.centerAnnotationView.center;
                         center.y += 20;
                         [self.centerAnnotationView setCenter:center];}
                     completion:nil];
}
//跳转设置页面
- (void)pushPhoneSetting {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}
#pragma mark - getter and setter
- (UIButton *)locationBtn {
    if (!_locationBtn) {
        _locationBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_locationBtn setBackgroundImage:[UIImage imageNamed:@"address_reset"] forState:UIControlStateNormal];
        [_locationBtn addTarget:self action:@selector(locationClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _locationBtn;
}
- (NSMutableArray *)commonPolylineArr {
    if (!_commonPolylineArr) {
        _commonPolylineArr = [[NSMutableArray alloc] init];
    }
    return _commonPolylineArr;
}
- (NSMutableArray *)searchArr {
    if (!_searchArr) {
        _searchArr = [[NSMutableArray alloc] init];
    }
    return _searchArr;
}
@end
